package com.coze.lg.cozeagent.controller;

import com.coze.lg.cozeagent.utils.Result;
import com.coze.openapi.client.audio.speech.CreateSpeechReq;
import com.coze.openapi.client.bots.CreateBotReq;
import com.coze.openapi.client.bots.CreateBotResp;
import com.coze.openapi.client.bots.ListBotReq;
import com.coze.openapi.client.bots.model.BotPromptInfo;
import com.coze.openapi.client.chat.CreateChatReq;
import com.coze.openapi.client.chat.model.ChatEvent;
import com.coze.openapi.client.chat.model.ChatEventType;
import com.coze.openapi.client.connversations.message.model.Message;
import com.coze.openapi.service.auth.TokenAuth;
import com.coze.openapi.service.config.Consts;
import com.coze.openapi.service.service.CozeAPI;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Collections;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.CompletableFuture;

@RestController
@RequestMapping("/coze")
public class CozeController {
    private final CozeAPI cozeAPI;
    String userID = "123";

    // 存储当前活跃的对话Disposable
    private final ConcurrentHashMap<String, Disposable> activeChats = new ConcurrentHashMap<>();
    // 用于生成对话ID
    private final AtomicLong chatCounter = new AtomicLong(0);

    public CozeController(CozeAPI cozeAPI) {
        this.cozeAPI = cozeAPI;
    }

    @Operation(description = "创建智能体")
    @PostMapping("/createBot")
    public Result BotPublishExample(String prompt , String name , String description ){
        BotPromptInfo promptInfo = new BotPromptInfo(prompt);
        CreateBotReq createReq = CreateBotReq.builder()
                .spaceID("7537235892172390434")
                .description(description)
                .name(name)
                .promptInfo(promptInfo)
                .build();
        CreateBotResp createResp = cozeAPI.bots().create(createReq);
        String botID = createResp.getBotID();
        System.out.println(createResp);
        return Result.success(true);
    }

    @Operation(description = "智能体对话")
    @PostMapping("/chat")
    public Result chat(String message , String botID ){
        // 生成唯一的对话ID
        String chatId = "chat_" + chatCounter.incrementAndGet();

        CreateChatReq req =
                CreateChatReq.builder()
                        .botID(botID)
                        .userID(userID)
                        .messages(Collections.singletonList(Message.buildUserQuestionText(message != null ? message : "你能做什么？")))
                        .build();

        StringBuilder fullResponse = new StringBuilder();
        Flowable<ChatEvent> resp = cozeAPI.chat().stream(req);

        // 创建Disposable并存储
        Disposable disposable = resp.subscribe(
                event -> {
                    if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) {
                        String content = event.getMessage().getContent();
                        fullResponse.append(content);
                        System.out.print(content);
                    }
                    if (ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(event.getEvent())) {
                        System.out.println("\nToken usage: " + event.getChat().getUsage().getTokenCount());
                        // 对话完成时移除
                        activeChats.remove(chatId);
                    }
                },
                error -> {
                    System.err.println("Chat error: " + error.getMessage());
                    activeChats.remove(chatId);
                },
                () -> {
                    System.out.println("done");
                    activeChats.remove(chatId);
                }
        );

        // 存储当前对话的Disposable
        activeChats.put(chatId, disposable);

        // 等待对话完成或被中断
        while (!disposable.isDisposed()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                break;
            }
        }

        return Result.success(fullResponse.toString());
    }

    @Operation(description = "中断当前对话")
    @PostMapping("/interruptChat")
    public Result interruptChat() {
        // 中断所有活跃对话
        for (Disposable disposable : activeChats.values()) {
            if (!disposable.isDisposed()) {
                disposable.dispose();
            }
        }
        activeChats.clear();
        System.out.println("All chats interrupted");
        return Result.success("All chats interrupted");
    }

    @Operation(description = "检查是否有活跃对话")
    @PostMapping("/hasActiveChat")
    public Result hasActiveChat() {
        boolean hasActive = !activeChats.isEmpty();
        for (Disposable disposable : activeChats.values()) {
            if (!disposable.isDisposed()) {
                hasActive = true;
                break;
            }
        }
        return Result.success(hasActive);
    }

    @Operation(description = "返回智能体列表")
    @PostMapping("/listBot")
    public Result listBot( String spaceID){
        ListBotReq req = ListBotReq.builder()
                .spaceID(spaceID)
                .build();
        return Result.success(cozeAPI.bots().list(req));
    }
    // 在 CozeController.java 中添加新的流式聊天方法
    @Operation(description = "流式智能体对话并转语音")
    @PostMapping("/streamChatWithSpeech")
    public void streamChatWithSpeech(String message, String botID, HttpServletResponse response) {
        try {
            // 设置响应头，表明返回的是音频流
            response.setContentType("audio/mp3");
            response.setHeader("Content-Disposition", "inline; filename=\"response.mp3\"");

            CreateChatReq req = CreateChatReq.builder()
                    .botID(botID)
                    .userID(userID)
                    .messages(Collections.singletonList(Message.buildUserQuestionText(message != null ? message : "你能做什么？")))
                    .build();

            Flowable<ChatEvent> resp = cozeAPI.chat().stream(req);

            // 创建音频输出流
            OutputStream audioOutputStream = response.getOutputStream();

            Disposable disposable = resp.subscribe(
                    event -> {
                        if (ChatEventType.CONVERSATION_MESSAGE_DELTA.equals(event.getEvent())) {
                            String content = event.getMessage().getContent();
                            System.out.print(content);

                            // 实时将文字转为语音并发送
                            byte[] speechData = textToSpeechData(content);
                            if (speechData != null) {
                                audioOutputStream.write(speechData);
                                audioOutputStream.flush();
                            }
                        }
                        if (ChatEventType.CONVERSATION_CHAT_COMPLETED.equals(event.getEvent())) {
                            System.out.println("\nToken usage: " + event.getChat().getUsage().getTokenCount());
                            // 完成后关闭流
                            audioOutputStream.close();
                        }
                    },
                    error -> {
                        System.err.println("Chat error: " + error.getMessage());
                        try {
                            audioOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    },
                    () -> {
                        System.out.println("Stream chat completed");
                        try {
                            audioOutputStream.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );

            // 存储Disposable以支持中断
            String chatId = "chat_" + chatCounter.incrementAndGet();
            activeChats.put(chatId, disposable);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 辅助方法：将文字转换为语音数据
    private byte[] textToSpeechData(String text) {
        try {
            CreateSpeechReq req = CreateSpeechReq.builder()
                    .input(text)
                    .voiceID("7426720361733013513")
                    .build();

            // 调用 Coze 的语音接口（具体实现取决于 SDK）
            // 这里需要根据实际的 Coze API 进行调整
            // 返回语音数据字节数组
            return new byte[0]; // 占位符，需要根据实际API实现
        } catch (Exception e) {
            System.err.println("Text to speech error: " + e.getMessage());
            return null;
        }
    }

}
